package risk.control.application.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import risk.control.application.activity.make.MakeActivity;
import risk.control.application.component.msg.ConfirmClickListener;
import risk.control.application.component.msg.ShowMsgDialog;

public class CameraPermissionHelper {

    public interface PermissionCallback {
        void onPermissionGranted();

        //void onPermissionDenied();
    }

    /**
     * 检查是否有摄像头权限
     */
    public static boolean hasCameraPermission(Context context) {
        return ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 申请摄像头权限（首次申请时显示解释对话框）
     */
    public static void requestCameraPermission(AppCompatActivity activity, ActivityResultLauncher<String> launcher, PermissionCallback callback) {

        if (hasCameraPermission(activity)) {
            callback.onPermissionGranted();
            return;
        }

        // 首次申请直接显示解释对话框
        showExplanationDialog(activity, launcher, callback);
    }

    /**
     * 显示权限解释对话框
     */
    private static void showExplanationDialog(AppCompatActivity activity, ActivityResultLauncher<String> launcher, PermissionCallback callback) {
        ShowMsgDialog showMsgDialog = new ShowMsgDialog(activity);
        showMsgDialog.setCancelable(false);
        showMsgDialog.setBtnText("授权");
        showMsgDialog.setBtnClickListener(new ConfirmClickListener() {
            @Override
            public void onPositiveClick() {
                // 用户同意后发起权限请求
                launcher.launch(Manifest.permission.CAMERA);
            }
        });
        showMsgDialog.showDialog("摄像头权限仅用于身份证识别转文字，拍摄后立即丢弃不会保存");

//        new AlertDialog.Builder(activity).setTitle("需要摄像头权限").setMessage("此功能需要使用您的摄像头进行拍照或录像").setPositiveButton("允许", (dialog, which) -> {
//
//        }).setNegativeButton("拒绝", (dialog, which) -> {
//            // 用户拒绝，只Toast提示
//            Toast.makeText(activity, "您拒绝了摄像头权限", Toast.LENGTH_SHORT).show();
//            callback.onPermissionDenied();
//        }).setCancelable(false).show();
    }

    /**
     * 创建权限请求Launcher
     */
    public static ActivityResultLauncher<String> createPermissionLauncher(AppCompatActivity activity, PermissionCallback callback) {

        return activity.registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
            if (isGranted) {
                callback.onPermissionGranted();
            } else {
                // 权限被拒绝，只Toast提示
                ToastUtils.showShort(activity, "您拒绝了摄像头权限");
                //callback.onPermissionDenied();
            }
        });
    }
}